package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 提交订单
     *
     * @param ordersSubmitDTO 订单提交数据传输对象
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // illegal check: if address is null, if cart is empty, etc.
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(ShoppingCart.builder()
                .userId(userId)
                .build());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        else if(shoppingCarts == null || shoppingCarts.isEmpty()){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // insert order
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setUserId(userId);
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Orders.UN_PAID);
        order.setUserName(userMapper.getById(userId).getName());
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());

        orderMapper.insert(order);
        Long orderId = order.getId();


        // insert order details
        List<OrderDetail> orderDetails = new ArrayList<>(shoppingCarts.size());
        shoppingCarts.forEach(cart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(orderId);

            orderDetails.add(orderDetail);
        });

        orderDetailMapper.insertBatch(orderDetails);

        // clear shopping cart
        shoppingCartMapper.deleteByUserId(userId);

        // encapsulate a OrderSubmitVO, return it
        return OrderSubmitVO.builder()
                .id(orderId)
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );


//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }

        // 假装支付成功
        JSONObject jsonObject = new JSONObject();
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        jsonObject.put("code", "ORDERPAID"); // 模拟订单已支付
        vo.setPackageStr(jsonObject.getString("package"));

        paySuccess(ordersPaymentDTO.getOrderNumber());

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);



        // 通过websocket向浏览器推送消息 type orderId content
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type", "1");   // 1 indicates order arrival message, 2 indicates user's order reminder
        map.put("orderId", ordersDB.getId());
        map.put("content", "一位用户刚刚支付了订单，\n订单号：" + ordersDB.getNumber()) ;

        JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }

    /**
     * 查询用户历史订单
     *
     * @param ordersPageQueryDTO 分页查询参数
     * @return 用户历史订单信息
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());

        // get order
        Page<OrderVO> list = orderMapper.list(ordersPageQueryDTO);

        // get and set order details
        list.forEach(orderVO -> {
            // 查询订单详情
            List<OrderDetail> orderDetailList = orderDetailMapper.listByOrderId(orderVO.getId());
            orderVO.setOrderDetailList(orderDetailList);

            // 拼接订单菜品信息
            StringBuilder orderDishes = new StringBuilder();
            orderDetailList.forEach(detail -> {
                orderDishes.append(detail.getName()).append(" x ").append(detail.getNumber()).append(", ");
            });
            if (orderDishes.length() > 0) {
                orderDishes.setLength(orderDishes.length() - 2); // 去掉最后的逗号和空格
            }
            orderVO.setOrderDishes(orderDishes.toString());
        });

        PageResult pageResult = new PageResult();
        pageResult.setTotal(list.getTotal());
        pageResult.setRecords(list.getResult());

        return pageResult;
    }

    /**
     * 根据订单号查询订单
     *
     * @return 订单信息
     */
    @Override
    public void cancelOrder(OrdersCancelDTO ordersCancelDTO) {
        // check if order is illegal
        Orders order = orderMapper.getById(ordersCancelDTO.getId());
        if(order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // update
        orderMapper.update(Orders.builder()
                .id(ordersCancelDTO.getId())
                .status(Orders.CANCELLED)
                .cancelReason(ordersCancelDTO.getCancelReason())
                .cancelTime(LocalDateTime.now())
                .build());
    }

    /**
     * 再来一单
     * @param id 订单号
     * @return
     */
    @Override
    public void repeatSubmit(Long id) {
        // get order detail
        List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(id);
        orderDetails.forEach(orderDetail -> {
            // add to shopping cart
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setName(orderDetail.getName());
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setDishId(orderDetail.getDishId());
            shoppingCart.setSetmealId(orderDetail.getSetmealId());
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setAmount(orderDetail.getAmount());
            shoppingCart.setImage(orderDetail.getImage());
            shoppingCart.setCreateTime(LocalDateTime.now());

            shoppingCartMapper.insert(shoppingCart);
        });
    }

    /**
     * 条件查询订单
     *
     * @param ordersPageQueryDTO 分页查询参数
     * @return 订单信息列表
     */
    @Override
    public PageResult list(OrdersPageQueryDTO ordersPageQueryDTO) {
        Page<OrderVO> list = orderMapper.list(ordersPageQueryDTO);

        return new PageResult(list.getTotal(), list.getResult());
    }

    /**
     * 订单统计
     *
     * @return 订单统计结果
     */
    @Override
    public OrderStatisticsVO getStatistics() {
        OrderStatisticsVO params = new OrderStatisticsVO();
        params.setConfirmed(Orders.CONFIRMED);
        params.setDeliveryInProgress(Orders.DELIVERY_IN_PROGRESS);
        params.setToBeConfirmed(Orders.TO_BE_CONFIRMED);

        return orderMapper.getStatistics(params);
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        // check if order is illegal
        Orders orderDB = orderMapper.getById(ordersConfirmDTO.getId());
        if (orderDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // update order
        orderMapper.update(Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build());
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orderDB = orderMapper.getById(ordersRejectionDTO.getId());
        if (orderDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        orderMapper.update(Orders.builder()
                .id(ordersRejectionDTO.getId())
                .status(Orders.REFUND_STATUS)
                .rejectionReason(ordersRejectionDTO.getRejectionReason())
                .build());
    }

    @Override
    public void delivery(Long id) {
        Orders order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        orderMapper.update(Orders.builder()
                .id(id)
                .status(Orders.DELIVERY_IN_PROGRESS)
                .build());
    }

    @Override
    public void complete(Long id) {
        Orders order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        orderMapper.update(Orders.builder()
                .id(id)
                .status(Orders.COMPLETED)
                .build());
    }

    /**
     * 根据订单ID查询订单及详细信息
     *
     * @param id 订单ID
     * @return 订单信息
     */
    @Override
    public OrderVO getByOrderId(Long id) {
        OrderVO orderVO = new OrderVO();

        Orders order = orderMapper.getById(id);
        BeanUtils.copyProperties(order, orderVO);
        List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(id);
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }

    @Override
    public void reminder(Long id) {
        Orders orderDB = orderMapper.getById(id);
        if (orderDB == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // send reminder message via websocket
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type", "2");   // 1 indicates order arrival message, 2 indicates user's order reminder
        map.put("orderId", id);
        map.put("content", "有个用户他催单了，订单号：" + orderDB.getNumber());

        webSocketServer.sendToAllClient(JSONObject.toJSONString(map));
    }
}
